<?php
/**
 * 用户导入页面
 * 相对路径: adm/usin.php
 * 作者: 15058593138@qq.com
 */

// 单个添加
if (isset($_GET['act']) && $_GET['act'] === 'add') {
    $phone = isset($_POST['phone']) ? safeStr($_POST['phone']) : '';
    $pwd = isset($_POST['pwd']) ? $_POST['pwd'] : '';
    
    if (empty($phone) || empty($pwd)) {
        jsonMsg(0, '请填写完整信息');
    }
    
    if (strlen($pwd) < 6) {
        jsonMsg(0, '密码长度不能少于6位');
    }
    
    $db = new DB();
    $userTable = TB_PREFIX . 'user';
    
    // 检查手机号是否存在
    $sql = "SELECT * FROM `{$userTable}` WHERE `手机号` = '{$phone}'";
    if ($db->getRow($sql)) {
        $db->close();
        jsonMsg(0, '该手机号已存在');
    }
    
    // 添加用户
    $pwdHash = pwdHash($pwd);
    $result = $db->insert($userTable, [
        '手机号' => $phone,
        '密码' => $pwdHash
    ]);
    
    $db->close();
    
    if ($result) {
        jsonMsg(1, '添加成功');
    } else {
        jsonMsg(0, '添加失败');
    }
}

// 批量导入
if (isset($_GET['act']) && $_GET['act'] === 'import') {
    $data = isset($_POST['data']) ? trim($_POST['data']) : '';
    
    if (empty($data)) {
        jsonMsg(0, '请粘贴导入数据');
    }
    
    $db = new DB();
    $userTable = TB_PREFIX . 'user';
    
    $lines = explode("\n", $data);
    $success = 0;
    $fail = 0;
    $exists = 0;
    
    foreach ($lines as $line) {
        $line = trim($line);
        if (empty($line)) continue;
        
        // 支持Tab或空格分隔
        $fields = preg_split('/\s+/', $line);
        if (count($fields) < 2) {
            $fail++;
            continue;
        }
        
        $phone = safeStr($fields[0]);
        $pwd = $fields[1];
        
        if (empty($phone) || empty($pwd)) {
            $fail++;
            continue;
        }
        
        // 检查是否存在
        $sql = "SELECT * FROM `{$userTable}` WHERE `手机号` = '{$phone}'";
        if ($db->getRow($sql)) {
            $exists++;
            continue;
        }
        
        // 插入用户
        $pwdHash = pwdHash($pwd);
        if ($db->insert($userTable, ['手机号' => $phone, '密码' => $pwdHash])) {
            $success++;
        } else {
            $fail++;
        }
    }
    
    $db->close();
    jsonMsg(1, "导入完成：成功{$success}条，失败{$fail}条，已存在{$exists}条");
}

require_once './inc/head.php';
?>

<div class="container">
    <div style="display:grid; grid-template-columns:1fr 1fr; gap:15px;">
        <!-- 单个添加 -->
        <div class="table-wrapper">
            <div style="padding:20px;">
                <h3>单个添加用户</h3>
                
                <form id="addForm" style="margin-top:20px;">
                    <div class="form-group">
                        <label>手机号</label>
                        <input type="text" name="phone" class="form-control" placeholder="请输入手机号" required>
                    </div>
                    
                    <div class="form-group">
                        <label>密码</label>
                        <input type="password" name="pwd" class="form-control" placeholder="请输入密码（至少6位）" required>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary">添加用户</button>
                        <button type="reset" class="btn btn-secondary">重置</button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 批量导入 -->
        <div class="table-wrapper">
            <div style="padding:20px;">
                <h3>批量导入用户</h3>
                
                <form id="importForm" style="margin-top:20px;">
                    <div class="form-group">
                        <label>导入数据（每行一个，格式：手机号 密码）</label>
                        <textarea name="data" class="form-control" rows="10" >13800000001 123456&#10;13800000002 123456&#10;13800000003 123456</textarea>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-success">批量导入</button>
                        <button type="reset" class="btn btn-secondary">清空</button>
                    </div>
                    
                    <div style="color:#666; font-size:12px; margin-top:10px;">
                        <p>说明：</p>
                        <ul style="margin-left:20px;">
                            <li>每行一个用户，手机号和密码用空格或Tab分隔</li>
                            <li>密码长度至少6位</li>
                            <li>已存在的手机号将被跳过</li>
                            <li>可以从Excel复制粘贴（保留Tab分隔）</li>
                        </ul>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    // 单个添加
    document.getElementById('addForm').onsubmit = function(e) {
        e.preventDefault();
        
        const formData = getFormData('addForm');
        
        ajax('admin.php?do=usin&act=add', formData, function(res) {
            if (res.code === 1) {
                toast(res.msg, 'success');
                document.getElementById('addForm').reset();
            } else {
                toast(res.msg, 'error');
            }
        });
    };
    
    // 批量导入
    document.getElementById('importForm').onsubmit = function(e) {
        e.preventDefault();
        
        const formData = getFormData('importForm');
        
        if (!formData.data) {
            toast('请输入导入数据', 'error');
            return;
        }
        
        showLoading();
        ajax('admin.php?do=usin&act=import', formData, function(res) {
            hideLoading();
            if (res.code === 1) {
                toast(res.msg, 'success', 5000);
                document.getElementById('importForm').reset();
            } else {
                toast(res.msg, 'error');
            }
        });
    };
</script>

<?php require_once './inc/foot.php'; ?>